<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-containers" v-if="isAdmin">
      <div class="filter-left">
        <el-input
          size="mini"
          v-model="listQuery.searchKey"
          placeholder="请输入用户名称或登录账号"
          style="width: 250px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @input="handleFilter"
        />
      </div>
      <div class="filter-right">
        <el-button
          icon="el-icon-plus"
          type="primary"
          size="mini"
          @click="handleAddInfo"
        >
          新增
        </el-button>
      </div>
    </div>
    <!-- table数据 -->
    <el-table
      :data="pageList"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="userName" label="用户名称" align="center">
      </el-table-column>
      <el-table-column prop="loginName" label="登录账号" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.loginName">{{row.loginName}}</span>
          <el-button v-else type="text" size="small" @click="handleChangeLoginName(row)"
            >编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="mfAuthId" label="唯一标识" align="center">
      </el-table-column>
      <el-table-column prop="mobileTxt" label="手机号" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.mobileTxt" style="margin-right:12px;">{{row.mobileTxt}}</span>
          <el-button v-if="isAdmin" type="text" size="small" @click="handleChangeUserMobile(row)"
            >编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="avatar" label="用户头像" align="center">
        <template slot-scope="{ row }">
          <img v-if="row.avatar" :src="row.avatar" style="width: 50px; height: 50px" />
          <img v-else src="https://morefun-active.oss-cn-beijing.aliyuncs.com/morefun_oa/mofun_OA_img/logo_img.png" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.status" type="danger">已冻结</el-tag>
          <el-tag v-if="!row.status" type="success">已启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="绑定状态" align="center">
        <template slot-scope="{ row }">
          <el-button v-if="!row.dingUnionId" type="text" size="small" @click="handleBindDingTalk(row)"
            >钉钉绑定</el-button
          >
          <el-button v-if="!row.weChatOpenId" type="text" size="small" @click="handleBingdWechat(row)"
            >微信绑定</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="lastLoginTime" label="最近登录时间" align="center">
      </el-table-column>
      
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button type="text" size="small" @click="handleChangeUserPassword(row)"
            >修改密码</el-button>
          <el-button
            type="text"
            size="small"
            style="color: green"
            @click="handleResetUserPassword(row)"
            >重置密码</el-button
          >
          <el-button
            type="text"
            size="small"
            v-if="row.status && isAdmin"
            @click="handleRestoreUserAccount(row)"
            >启用</el-button
          >
          <el-button
            type="text"
            size="small"
            style="color: red"
            v-if="!row.status && isAdmin"
            @click="handleFreezeUserAccount(row)"
            >冻结</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getUserLists"
    />

    <!-- 新增修改信息 -->
    <el-drawer
      size="50%"
      :close-on-press-escape="false"
      :visible.sync="dialogFormVisible"
      :wrapperClosable="false"
      :title="title"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" label-width="135px" prop="userName">
              <el-input
                v-model="form.userName"
                autocomplete="off"
                maxlength="100"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="登录账号" label-width="135px" prop="loginName">
              <el-input
                v-model="form.loginName"
                autocomplete="off"
                maxlength="100"
                placeholder="请输入登录账号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item
              label="密码"
              label-width="135px"
            >
              <span>{{form.password}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="text" @click="handleGetNewWord(1)">再来一个</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="text" @click="handleCopy(form.password)">复制</el-button>
          </el-col>
        </el-row>
      </el-form>
      <div class="el_drawer_footerbtn">
        <el-button style="margin: 0 10px" @click="handleCancel"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleSubmit('form')"
          >确 定</el-button
        >
      </div>
    </el-drawer>
    <!-- 重置密码、修改密码 -->
    <el-drawer
      size="50%"
      :close-on-press-escape="false"
      :visible.sync="dialogPasswordVisible"
      :wrapperClosable="false"
      :title="dialogPasswordVisibleTitle"
    >
      <div style="margin:12px;color:#E6A23C;">
        <b>注意：</b>密码为6-36位</div>
      <el-form ref="form" :model="dialogPasswordForm">
        <el-row v-if="dialogPasswordStatus == 'change'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="旧密码" label-width="135px">
                <el-input
                  v-model="dialogPasswordForm.oldPassword"
                  autocomplete="off"
                  maxlength="36"
                  minlength="6"
                  placeholder="请输入旧密码"
                  show-password
                  type="password"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="新密码" label-width="135px">
                <el-input
                  v-model="dialogPasswordForm.newPassword"
                  autocomplete="off"
                  maxlength="36"
                  minlength="6"
                  placeholder="请输入新密码"
                  show-password
                  type="password"
                  @input="handlePasswordInpt"
                ></el-input>
                <div style="width:50%;margin-top:8px;">
                  <el-progress :percentage="percentage" :color="customColors" :format="format"></el-progress>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="自动生成" label-width="135px">
                <span style="margin-right:12px;">{{dialogPasswordForm.autoPassword}}</span>
                <el-button type="text" @click="handleGetNewWord(3)">点击获取</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
        <el-row v-if="dialogPasswordStatus == 'reset'">
          <el-col :span="10">
            <el-form-item
              label="密码"
              label-width="135px"
            >
              <el-input
                  v-model="dialogPasswordForm.password"
                  autocomplete="off"
                  maxlength="36"
                  minlength="6"
                  placeholder="请输入新密码"
                  show-password
                  type="password"
                  @input="handlePasswordInpt"
                ></el-input>
                <div style="width:50%;margin-top:8px;">
                  <el-progress :percentage="percentage" :color="customColors" :format="format"></el-progress>
                </div>
                
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="text" @click="handleGetNewWord(2)">再来一个</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="text" @click="handleCopy(dialogPasswordForm.password)">复制</el-button>
          </el-col>
        </el-row>
      </el-form>
      <div class="el_drawer_footerbtn">
        <el-button style="margin: 0 10px" @click="handleCancelPassword"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleSubmitPassword('form')"
          >确 定</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>
  <script>
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
// 导入模块
import vueJsonEditor from "vue-json-editor";
import { curentTime } from "@/filters/index";
import { 
  getUserList,
  setUserInfo,
  changeUserPassword,
  resetUserPassword,
  freezeUserAccount,
  restoreUserAccount,
  bindUserLoginName,
  bindUserMobile
  } from "@/api/accreditUser";
import { setEncryptStrData } from "@/utils/jsencrypt";
import { v4 as uuidv4 } from 'uuid';
import randomPassword from 'random-password';
import { mapGetters } from "vuex"
import handleClipboard from "@/utils/clipboard";
export default {
  name: "Accredit",
  components: { Pagination, vueJsonEditor },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  computed: {
    ...mapGetters([
      'roles'
    ]),
  },
  data() {
    return {
      // 表单控制
      dialogFormVisible: false,
      // 表单标题
      title: "",
      //   表单
      form: {
        id: "",
        userName: "",
        loginName: "",
        password: "",
      },
      formType: "",
      // 表单检验
      rules: {
        userName: [{ required: true, message: "请填写名称", trigger: "blur" }],
        loginName: [
          { required: true, message: "请填写完成跳转路径", trigger: "blur" },
        ],
      },
      // 请求方式
      methodTypeLists: ["GET", "POST"],
      webapiDataObj: null,
      // table数据
      pageList: [],
      // 查询参数
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        searchKey: null,
      },
      //  总数量
      total: 0,
      pdfhref: "https://morefun.yuque.com/kd0dsy/pyy99r/ryr6mfciblufutqk",
      pageToken: "",
      dialogPasswordVisible: false,
      dialogPasswordVisibleTitle: "",
      dialogPasswordStatus: "",
      dialogPasswordForm: {
        id: "",
        oldPassword: "",
        newPassword: "",
        password: "",
        autoPassword: ""
      },
      percentage: 0,
      customColors: '#fff',
      isAdmin: false,
    };
  },
  async created() {
    this.getUserLists();
    this.isAdmin = this.roles.includes('admin');
  },
  methods: {
    // 邮箱内容更新
    handleChangeLoginName(row){
      this.$prompt('请输入登录账号', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async ({ value }) => {
          await this.dealAjaxHeaders();
          const res = await bindUserLoginName({
            "id": row.id,
            "loginName": value
          });
          if(res.success){
            this.$message({ message: "更新成功", type: "success" });
            this.getUserLists();
          }else{
            this.$message({ message: res.errorMsg || "更新失败", type: "error" });
          }
        }).catch(() => {      
        });
    },
    // 手机号更新
    handleChangeUserMobile(row){
      this.$prompt('请输入手机号', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async ({ value }) => {
          const _value = value.trim();
          if(/^1\d{10}$/.test(_value)){
            await this.dealAjaxHeaders();
            const res = await bindUserMobile({
              "id": row.id,
              "mobile": _value
            });
            if(res.success){
              this.$message({ message: "更新成功", type: "success" });
              this.getUserLists();
            }else{
              this.$message({ message: res.errorMsg || "更新失败", type: "error" });
            }
          }else{
            this.$message({ message: "请输入正确的11位手机号", type: "error" });
          }
        }).catch(() => {      
        });
    },
    //  请求头准备
    async dealAjaxHeaders() {
      const _uid = uuidv4();
      const _loginEncrypt = await setEncryptStrData(_uid);
      return await this.$store.dispatch("user/setMfAgent", {uuid:_uid, agentId:_loginEncrypt});
    },
    //  密码强弱度校验
    handlePasswordInpt(password){
      const hasUpperCase = /[A-Z]/.test(password);
      const hasLowerCase = /[a-z]/.test(password);
      const hasNumbers = /\d/.test(password);
      const hasSpecialChars = /[\W_]/.test(password);
    
      // 大小写字母、数字、特殊字符
      const caseBonus = hasUpperCase && hasLowerCase ? 1 : 0;
      const numberBonus = hasNumbers ? 1 : 0;
      const specialCharBonus = hasSpecialChars ? 1 : 0;
      // 总分
      const totalScore = caseBonus + numberBonus + specialCharBonus;
      if(totalScore == 1){
        this.percentage = 33;
        this.customColors = '#F56C6C';
      }else if(totalScore == 2){
        this.percentage = 66;
        this.customColors = '#E6A23C';
      }else if(totalScore == 3){
        this.percentage = 100;
        this.customColors = '#67C23A';
      }
    },
    // 强弱度进度条
    format(percentage) {
      return percentage >= 90 ? '强' : percentage >= 60 ? '中' : '弱';
    },
    // 密码修改和重置提交
    async ajaxSubmitPassword(){
      if(this.dialogPasswordStatus == "change"){
        if(this.dialogPasswordForm.oldPassword && this.dialogPasswordForm.newPassword){
          const changeRes = await changeUserPassword({
            "old": this.dialogPasswordForm.oldPassword,
            "cur": this.dialogPasswordForm.newPassword
          },this.dialogPasswordForm.id);
          if(changeRes && changeRes.success){
            this.$message({
              message: "操作成功",
              type: "success",
            })
            this.handleCancelPassword();
            this.getUserLists();
          }else{
            this.$message({
              message: changeRes.errorMsg || "操作失败",
              type: "error",
            });
          }
        }else{
          this.$message({
            message: "请填写旧密码和新密码",
            type: "error",
          });
        }
      }else if(this.dialogPasswordStatus == "reset"){
        if(this.dialogPasswordForm.password){
          const res = await resetUserPassword({
            "pwd": this.dialogPasswordForm.password
          },this.dialogPasswordForm.id);
          if(res && res.success){
            this.$message({
              message: "操作成功",
              type: "success",
            })
            this.handleCancelPassword();
            this.getUserLists();
          }else{
            this.$message({
              message: res.errorMsg || "操作失败",
              type: "error",
            });
          }
        }else{
          this.$message({
            message: "请填写新密码",
            type: "error",
          });
        }
      }
    },
    async handleSubmitPassword(){
      await this.dealAjaxHeaders();
      this.ajaxSubmitPassword();
    },
    handleCancelPassword(){
      this.percentage = 0;
      this.customColors = '#fff';
      this.dialogPasswordVisible = false;
      this.dialogPasswordVisibleTitle = "";
      this.dialogPasswordStatus = "";
      this.dialogPasswordForm = {
        id: "",
        oldPassword: "",
        newPassword: "",
        password: "",
        autoPassword: ""
      };
    },
    // 修改密码
    handleChangeUserPassword(row){
      this.dialogPasswordVisible = true;
      this.dialogPasswordVisibleTitle = "修改密码";
      this.dialogPasswordStatus = "change";
      this.dialogPasswordForm = {
        id: row.id,
        oldPassword: "",
        newPassword: "",
        password: "",
        autoPassword: ""
      };
    },
    //  重置密码
    handleResetUserPassword(row){
      this.dialogPasswordVisible = true;
      this.dialogPasswordVisibleTitle = "重置密码";
      this.dialogPasswordStatus = "reset";
      this.dialogPasswordForm = {
        id: row.id,
        oldPassword: "",
        newPassword: "",
        password: ""
      };
    },
    //  冻结账户
    async handleFreezeUserAccount(row){
      if(!this.isAdmin) return this.$message({ type: 'error', message: '只有管理员才能操作' });

      this.$confirm('确定冻结当前账号？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.dealAjaxHeaders();
        const ajaxres = await freezeUserAccount(row.id);
        if(ajaxres && ajaxres.success){
          this.$message({
            type: 'success',
            message: '操作成功'
          });
          this.getUserLists();
        }else{
          this.$message({
            type: 'error',
            message: ajaxres.errorMsg || '操作失败'
          });
        }
      }).catch(() => {});
    },
    //  恢复账户
    handleRestoreUserAccount(row){
      if(!this.isAdmin) return this.$message({ type: 'error', message: '请联系管理员执行该操作' });

      this.$confirm('确定启用当前账号？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.dealAjaxHeaders();
        const ajaxres = await restoreUserAccount(row.id);
        if(ajaxres && ajaxres.success){
          this.$message({
            type: 'success',
            message: '操作成功'
          });
          this.getUserLists();
        }else{
          this.$message({
            type: 'error',
            message: ajaxres.errorMsg || '操作失败'
          });
        }
      }).catch(() => {});
    },
    //  获取新密码
    handleGetNewWord(type){
      if(type == 1){
        this.form.password = randomPassword(16);
      }else if(type == 2){
        this.dialogPasswordForm.password = randomPassword(16);
        this.handlePasswordInpt(this.dialogPasswordForm.password);
      }else if(type == 3){
        this.dialogPasswordForm.autoPassword = randomPassword(16);
      }
    },
    //  列表查询
    async getUserLists(){
      try{
        const _uid = uuidv4();
        const _loginEncrypt = await setEncryptStrData(_uid);
        const _listsRes = await getUserList({
          ...this.listQuery,
          mfagentid: _loginEncrypt,
          mfuuid: _uid
        });
        if(_listsRes.success && _listsRes.data && _listsRes.data.totalSize){
          this.pageList = _listsRes.data.data;
          this.total = _listsRes.data.totalSize;
        }else{
          this.pageList = [];
        }
      }catch(e){
        this.$message({
          type: 'error',
          message: '数据查询失败'
        })
      }
    },
    async handleBindDingTalk(row){
      this.$message('暂未开放')
    },
    async handleBingdWechat(row){
      this.$message({
        type: 'info',
        message: '暂未开放',
      })
    },
    // 按需查询
    async handleFilter() {
      this.listQuery.pageNum = 1;
      this.getUserLists();
    },

    // 新增授权方法
    handleAddInfo() {
      this.title = "新增账号";
      this.formType = "add";
      delete this.form.id;
      this.form.userName = "";
      this.form.loginName = "";
      this.form.password = randomPassword(16);
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
      });
      this.dialogFormVisible = true;
    },
    // 提交表单信息
    handleSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.form.id) {
            updateAuth(this.form).then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.getUserLists();
              this.dialogFormVisible = false;
            });
          } else {
            delete this.form.id;
            this.insertNewUser(this.form);
          }
        }
      });
    },
    // 新增用户
    async insertNewUser(){
      await this.dealAjaxHeaders();
      const _insertRes = await setUserInfo({
        "userName": this.form.userName,
        "loginName":this.form.loginName,
        "password": this.form.password,
      });
      if(_insertRes.success){
        this.getUserLists();
        this.dialogFormVisible = false;
      }else{
        this.$message({
          type: 'error',
          message: _insertRes.errorMsg || '新增失败'
        })
      }
    },

    // 取消
    handleCancel() {
      this.dialogFormVisible = false;
    },
    handleCopy(value) {
      let name = value; //每一行的某个值
      var copyContent = document.createElement("input"); //创建一个隐藏input（重要！）
      copyContent.value = name; //拼接多个赋值
      document.body.appendChild(copyContent);
      copyContent.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      this.$message.success("复制成功！");
      copyContent.remove();
    },
  },
};
</script>
    
    <style lang="scss">
.filter-containers {
  display: flex;
  justify-content: space-between;
  margin-bottom: 18px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
      